<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学期名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入学期名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['course:timetable:edit']"
          >新增</el-button>
      </el-form-item>
    </el-form>


    <el-table v-loading="loading" :data="timetableList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="学期名称" align="center" prop="courseName" show-overflow-tooltip/>
      <el-table-column label="起始日期" align="center" prop="courseStartDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.courseStartDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="courseEndDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.courseEndDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学年" align="center" prop="xn">
      </el-table-column>
      <el-table-column label="学期" align="center" prop="xq" :formatter="xqFormat">
      </el-table-column>
      <el-table-column label="编辑人员" align="center" prop="updateBy"  />
      <el-table-column label="编辑时间" align="center" prop="updateTime" width="160"/>
      <el-table-column label="操作" align="center"  width="100"
      v-if="isPermit('course:timetable:edit')">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['course:timetable:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['course:timetable:edit']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程时间对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="学期名称" prop="courseName">
          <el-input v-model="form.courseName" placeholder="请输入学期名称" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="学年" prop="xn">
              <el-input v-model="form.xn" placeholder="请输入学年(yyyy-yyyy)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学期" prop="xq">
              <el-select
                class="input_w"
                v-model="form.xq"
                placeholder="请选择学期">
                <el-option
                  v-for="dict in xqOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="起始日期" prop="courseStartDate">
              <el-date-picker clearable style="width: 100%"
                v-model="form.courseStartDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择起始日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="courseEndDate">
              <el-date-picker clearable style="width: 100%"
                v-model="form.courseEndDate"
                type="date"n
                value-format="yyyy-MM-dd"
                placeholder="选择结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="截止日期" prop="lastDate">
              <el-date-picker clearable style="width: 100%"
                v-model="form.lastDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择截止日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <span style="margin-left: 10px;line-height: 36px;">(包含假期)</span>
          </el-col>
        </el-row>
        <el-row v-for="(item, index) in form.courseOffDayList" :key="index">
          <el-col :span="12">
            <el-form-item label="学期内节日"
            :prop="'courseOffDayList.' + index + '.date'">
            <el-date-picker clearable style="width: 100%"
              v-model="item.date"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="节日名称"
            :prop="'courseOffDayList.' + index + '.name'">
              <el-input v-model="item.name" placeholder="请输节日名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button @click="addOffDay">新增节日</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTimetable, getTimetable, delTimetable, addTimetable, updateTimetable, exportTimetable } from "@/api/course/timetable";
export default {
  name: "Timetable",
  data() {
      var validatorCourseEndDate = (rule, value, callback) => {
        if (value <= this.form.courseStartDate) {
          callback(new Error('学期结束日期必须大于学期开始日期'))
        }
        callback()
      }

    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程时间表格数据
      timetableList: [],
      xqOptions:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseName: null,
        courseStartDate: null,
        courseEndDate: null,
        firstWeekStart: null,
        firstWeekEnd: null,
      },
      // 表单参数
      form: {
        courseOffDayList: [{
          date: null,
          name: null
        }],
      },
      // 表单校验
      rules: {
        courseName: [
          { required: true, message: "课表名称不能为空", trigger: "blur" }
        ],
        courseStartDate: [
          { required: true, message: "课表起始日期不能为空", trigger: "blur" }
        ],
        courseEndDate: [
          { required: true, message: "课表结束日期不能为空", trigger: "blur" },
          { validator: validatorCourseEndDate, trigger: "blur" }
        ],
        lastDate: [
          { required: true, message: "学期截止日期不能为空", trigger: "blur" }
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("xqOpt").then(response => {
        this.xqOptions = response.data;
    });
  },
  methods: {
    xqFormat(row, column) {
      return this.selectDictLabel(this.xqOptions, row.xq);
    },
    /** 查询课程时间列表 */
    getList() {
      this.loading = true;
      listTimetable(this.queryParams).then(response => {
        this.timetableList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        timetableId: null,
        courseName: null,
        courseStartDate: null,
        courseEndDate: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        courseOffDayList: [{
          date: null,
          name: null
        }],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.timetableId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增学期日历";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const timetableId = row.timetableId || this.ids
      getTimetable(timetableId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改学期日历";
      });
    },
    addOffDay() {
      this.form.courseOffDayList.push({
        date: null,
        name: null
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.timetableId != null) {
            updateTimetable(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTimetable(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const timetableIds = row.timetableId || this.ids;
      this.$confirm('是否确认删除课程时间编号为"' + timetableIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delTimetable(timetableIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有课程时间数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportTimetable(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    /** 管理课程操作 */
    handleCourse(row) {
      this.$router.push({ path: 'course', query: {id: row.timetableId}})
    },
    isPermit(permitKey){
      if(this.$store.state.user.name=='admin'){
        return true;
      }
      let  permissions = this.$store.getters.permissions;
      return permissions.includes(permitKey);
    },
  }
};
</script>
